/**
 * @package 全局相应拦截, 统一返回体内容
 * @author liu
 */

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor
} from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import type { Request } from 'express'

import { I_Response } from '../../../types/type'

@Injectable()
export class ResponseInterceptor<T>
  implements NestInterceptor<T, I_Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler<T>
  ): Observable<I_Response<T>> {
    const request = context.switchToHttp().getRequest<Request>()
    return next.handle().pipe(
      map((res: I_Response<T>) => {
        const {
          code = 200,
          message = '请求成功',
          success = true,
          data = null
        } = res
        const obj: I_Response<T> = {
          code,
          message,
          success,
          [data ? 'data' : Symbol.for('data')]: data
        }
        if (!success) {
          obj.request = {
            url: request.url,
            method: request.method,
            [Object.keys(request.body).length ? 'body' : Symbol.for('body')]:
              request.body,
            [Object.keys(request.query).length ? 'query' : Symbol.for('query')]:
              request.query,
            [Object.keys(request.params).length
              ? 'params'
              : Symbol.for('params')]: request.params,
            timestamp: (Date.now() + 1000 * 60 * 60 * 8).toString()
          }
        }
        return obj
      })
    )
  }
}
